package com.xsomnus.open.im.demo.netty.hi;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.Date;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/24 0024 14:44
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
public class FirstClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date() + ": 客户端写出数据");
        for (int i = 0; i < 1000; i++) {
            // (1) 构造数据
            ByteBuf buf = getByteBuf(ctx);
            // (2) 写数据
            ctx.channel().writeAndFlush(buf);
        }
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        byte[] bytes = "你好, 服务端!让我们做个朋友吧!\n".getBytes(Charset.forName("UTF-8"));
        ByteBuf byteBuf = ctx.alloc().buffer();
        byteBuf.writeBytes(bytes);
        return byteBuf;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println(new Date() + ": 客户端从服务读取到的数据是 => " + byteBuf.toString(Charset.forName("UTF-8")));
    }
}
